(function() {
  var UpdateService, auth_server, crypto, fs, iced, request, update_server, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  fs = require('fs');

  crypto = require('crypto');

  request = require('request');

  update_server = process.env.UPDATE_SERVER || 'https://update.forensix.cn';

  auth_server = process.env.AUTH_SERVER || 'https://account.forensix.cn';

  UpdateService = (function() {
    function UpdateService(_clientId, _clientSecret) {
      this._clientId = _clientId;
      this._clientSecret = _clientSecret;
      this._jar = request.jar();
    }

    UpdateService.prototype.login = function(username, password, cb) {
      var body, e, err, form, resp, state, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            funcname: "UpdateService.login"
          });
          request.get(update_server + '/auth/honglian', {
            jar: _this._jar,
            followRedirect: false
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                resp = arguments[1];
                return body = arguments[2];
              };
            })(),
            lineno: 14
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          var _ref;
          if (err) {
            return cb(err);
          }
          state = ((_ref = resp.headers.location) != null ? _ref.split('&state=')[1] : void 0) || '';
          form = {
            'username': username,
            'password': password,
            'client_id': 'UPDATESERVICE',
            'redirect_uri': update_server + '/auth/honglian/callback',
            'grant_type': 'password',
            'scope': 'profile',
            'response_type': 'code'
          };
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              funcname: "UpdateService.login"
            });
            request.post(auth_server + '/oauth/login/authorise', {
              form: form,
              jar: _this._jar
            }, __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  err = arguments[0];
                  resp = arguments[1];
                  return body = arguments[2];
                };
              })(),
              lineno: 28
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (err) {
              return cb(err);
            }
            try {
              body = JSON.parse(body);
            } catch (_error) {
              e = _error;
              return cb(e);
            }
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                funcname: "UpdateService.login"
              });
              request.get(update_server + '/auth/honglian/callback?code=' + body['authCode']['authorizationCode'] + '&state=' + state, {
                jar: _this._jar
              }, __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    err = arguments[0];
                    resp = arguments[1];
                    return body = arguments[2];
                  };
                })(),
                lineno: 36
              }));
              __iced_deferrals._fulfill();
            })(function() {
              if (err) {
                return cb(err);
              }
              if (resp.statusCode !== 200) {
                console.log(body);
                return cb('登录更新服务失败！');
              } else {
                console.log('登录更新服务成功');
                return cb(null);
              }
            });
          });
        };
      })(this));
    };

    UpdateService.prototype.upload = function(param, cb) {
      var body, err, formData, matches, resp, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      formData = {
        software: param.client_name,
        version: param.version,
        description: param.description,
        files: [fs.createReadStream(param.path)]
      };
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            funcname: "UpdateService.upload"
          });
          request.post(update_server + '/upload/', {
            formData: formData,
            jar: _this._jar
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                resp = arguments[1];
                return body = arguments[2];
              };
            })(),
            lineno: 58
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if (err) {
            return cb(err);
          }
          if (resp.statusCode !== 302) {
            matches = body.match(/<h4>失败原因：(.*)<\/h4>/);
            return cb(matches ? matches[1] : body);
          }
          console.log('上传新版本成功');
          return cb(null);
        };
      })(this));
    };

    UpdateService.prototype.uploadComponents = function(components, cb) {
      var body, comp, err, formData, matches, md5, resp, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      formData = {
        client_id: this._clientId,
        client_secret: this._clientSecret,
        compsInfo: [],
        files: []
      };
      (function(_this) {
        return (function(__iced_k) {
          var _i, _len, _ref, _results, _while;
          _ref = components;
          _len = _ref.length;
          _i = 0;
          _while = function(__iced_k) {
            var _break, _continue, _next;
            _break = __iced_k;
            _continue = function() {
              return iced.trampoline(function() {
                ++_i;
                return _while(__iced_k);
              });
            };
            _next = _continue;
            if (!(_i < _len)) {
              return _break();
            } else {
              comp = _ref[_i];
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  funcname: "UpdateService.uploadComponents"
                });
                _this.md5File(comp.path, __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      err = arguments[0];
                      return md5 = arguments[1];
                    };
                  })(),
                  lineno: 76
                }));
                __iced_deferrals._fulfill();
              })(function() {
                if (err) {
                  return cb(err);
                }
                comp.md5 = md5;
                formData.compsInfo.push(JSON.stringify(comp));
                return _next(formData.files.push(fs.createReadStream(comp.path)));
              });
            }
          };
          _while(__iced_k);
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              funcname: "UpdateService.uploadComponents"
            });
            request.post(update_server + '/api/components/', {
              formData: formData,
              jar: _this._jar
            }, __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  err = arguments[0];
                  resp = arguments[1];
                  return body = arguments[2];
                };
              })(),
              lineno: 82
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (err) {
              return cb(err);
            }
            if (resp.statusCode !== 200) {
              matches = body.match(/<h4>失败原因：(.*)<\/h4>/);
              return cb(matches ? matches[1] : body);
            }
            console.log('上传组件成功');
            return cb(null);
          });
        };
      })(this));
    };

    UpdateService.prototype.md5File = function(filename, cb) {
      var input, output;
      output = crypto.createHash('md5');
      input = fs.createReadStream(filename);
      input.on('error', cb);
      output.once('readable', function() {
        return cb(null, output.read().toString('hex'));
      });
      return input.pipe(output);
    };

    return UpdateService;

  })();

  module.exports = UpdateService;

}).call(this);
